<script setup>
import { ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ZegoExpressEngine } from "zego-express-engine-webrtc";
import { getZgUserToken } from "@/api/login";

const router = useRouter();
const store = useStore();
const roomId = store.state.roomId;
const username = store.state.user;

const isSub = ref(false);

let zg = null;
let streamID = "";
let remoteStream = null;

const subTitle = `roomId:${roomId}  username:${username} `;
const appId = 11478049;
const secret = `a601e7de5756c85ac6d8a4840804136a`;
const server = `wss://webliveroom11478049-api.imzego.com/ws`;

//订阅
const handleSub = () => {
  isSub.value = !isSub.value;
  subVideo(roomId, username, appId, secret, server, "remote");
};
//断开
const handleClose = () => {
  isSub.value = !isSub.value;
  if (zg) {
   zg.logoutRoom(roomId);
    // 根据本端 streamID 停止推流
   //  zg.stopPublishingStream(streamID);
    // localStream 是调用 createZegoStream 接口获取的 ZegoLocalStream 实例对象
    zg.destroyStream(remoteStream);
    zg = null;
    remoteStream = null;
  }
};
//返回
const handleBack = () => {
  handleClose();
  router.push({ name: "Home" });
};
const subVideo = async (
  roomId,
  userName,
  appId,
  secret,
  server,
  remoteDivId
) => {
  zg = new ZegoExpressEngine(appId, server);
  const config = {
    logLevel: "warn",
  };
  zg.setLogConfig(config);
  zg.on(
    "roomStreamUpdate",
    async (roomID, updateType, streamList, extendedData) => {
      // 房间内其他用户音视频流变化的通知
      if (updateType == "ADD") {
        // 流新增，开始拉流
        // 此处演示拉取流新增的列表中第一条流的音视频
        streamID = streamList[0].streamID;
        // streamList 中有对应流的 streamID
        remoteStream = await zg.startPlayingStream(streamID);
        // 创建媒体流播放组件
        const remoteView = zg.createRemoteStreamView(remoteStream);
        remoteView.play(remoteDivId, { enableAutoplayDialog: true });
      } else if (updateType == "DELETE") {
        // 流删除，通过流删除列表 streamList 中每个流的 streamID 进行停止拉流。
        const streamID = streamList[0].streamID;
        zg.stopPlayingStream(streamID);
      }
    }
  );

  const userID = new Date().getTime().toString();
  const postData = {
    appId,
    userId: userID,
    secret,
  };
  const token = await getZgUserToken(postData);
  zg.loginRoom(roomId, token, { userID, userName }, { userUpdate: true }).then(
    async (result) => {
      if (result == true) {
        console.log("login success", result);
      }
    }
  );
};
</script>

<template>
  <div class="con--warp">
    <div class="title">
      <a-page-header
        style="border: 1px solid rgb(235, 237, 240)"
        title="订阅"
        :sub-title="subTitle"
        @back="handleBack"
      />
    </div>

    <div class="remote" id="remote"></div>

    <div class="btn--wrap">
      <a-space>
        <a-button type="primary" v-show="!isSub" @click="handleSub"
          >订阅</a-button
        >
        <a-button type="primary" v-show="isSub" @click="handleClose"
          >断开</a-button
        >
      </a-space>
    </div>
  </div>
</template>

<style scoped lang="scss">
.con--warp {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
  .title {
    position: absolute;
    left: 20px;
    top: 20px;
  }
  .btn--wrap {
    width: 500px;
  }
}
</style>
